package org.happycomp.radio.scheduler;

import java.io.File;
import java.io.IOException;
import java.util.TimerTask;
import java.util.logging.Level;

import org.happycomp.radio.Playlist;
import org.happycomp.radio.Station;
import org.happycomp.radio.StopDownloadCondition;
import org.happycomp.radio.StoreStateException;
import org.happycomp.radio.planner.PlannedItem;
import org.happycomp.radio.planner.Planner;

public class SchedulerTask extends TimerTask {
	
	public static final java.util.logging.Logger LOGGER = java.util.logging.Logger
			.getLogger(SchedulerTask.class.getName());
	
	private Scheduler scheduler;
	private Planner planner;
	
	public SchedulerTask(Scheduler scheduler, Planner planner) {
		super();
		this.scheduler = scheduler;
		this.planner = planner;
	
	}


	@Override
	public void run() {
		try {
			planner.getPlannerLock().lock();
			final PlannedItem plannedItem = planner.popNext();
			if (plannedItem != null) {
				final Station station = plannedItem.getStation();
				final StopDownloadCondition condition = plannedItem.getCondition();
				new Thread() {
					public void run() {
						try {
							LOGGER.info("starting download ..");
							//Downloader downloader = new DownloaderImpl(scheduler);
							Playlist playList = scheduler.getDownloader().getPlayList(station);
							LOGGER.info(""+playList.getEntries().size());
							scheduler.getDownloader().download(playList, plannedItem.getTitle(), new File(System.getProperty("user.dir")), condition, plannedItem.getId());
						} catch (IOException e) {
							scheduler.fireException(e);
						    LOGGER.log(Level.SEVERE,e.getMessage(),e);
						} catch (StoreStateException e) {
							LOGGER.log(Level.SEVERE,e.getMessage(),e);
						} catch (Exception e) {
							scheduler.fireException(e);
						    LOGGER.log(Level.SEVERE,e.getMessage(),e);
						}
					}
				}.start();
			} else {
				LOGGER.info("no plan item !");
			}
		} finally {
			planner.getPlannerLock().unlock();
		}
		
		this.scheduler.scheduleCheck();
	}
	
}
